
const MONTH_FIELD = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'act', 'nov', 'dec'];
const MONTH_TITLE = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];


$(function () {
    layui.use(['jquery', 'form', 'layer', 'table', 'laytpl', 'laydate', 'element'], function() {
        var $ = layui.jquery, form = layui.form, layer = layui.layer, table = layui.table,
            laydate = layui.laydate;

        //表格渲染
        /**
         * 更新数据表格
         * @type {{init:function, update:function}}
         */
        let Render = (function () {
            const col = (function () {
                let list = [];
                list.push({
                    field: 'type', title: '类型', width: 120
                });
                for(let i in MONTH_FIELD){
                    list.push({
                        field: MONTH_FIELD[i],
                        title: MONTH_TITLE[i],
                        sort: true,
                        width: 100
                    })
                }
                list.push({
                    field: 'total', title: '合计', width: 90
                });
                return list;
            })();

            let complete = function(){
                window.resizeWindowHeight?window.resizeWindowHeight():'';
            };

            /**
             * 初始化
             * @param {{selector:string, title:string, data: Array}} setting
             */
            let init = function (setting) {
                table.render({
                    title: setting.title,
                    elem: setting.selector,
                    page: false,
                    width: '100%',
                    even: true, //隔行背景
                    size: 'sm', //大尺寸的表格
                    cellMinWidth: 20,
                    toolbar: true,
                    cols: [col],
                    data: setting.data,
                    done: function () {
                        complete();
                    }

                });
            };

            /**
             * 更新
             * @param {{selector:string, title:string, data: Array}} setting
             */
            let update = function (setting) {
                table.reload(setting.selector, {
                    title: setting.title,
                    data: setting.data,
                });
            };
            return {
                init: init,
                update: update
            };
        })();

        //拉取数据
        let fetch = function(setting){
            let loadingLayer = layer.load(2, {time: 10*1000});
            $.ajax({
                url: 'selectTotalExpense',
                data: setting.formData,
                success: (res)=>{
                    if(res.code == 0){
                        let data = res.data;
                        if(!data){
                            if(setting.success){
                                setting.success({
                                    TOTFY: [],
                                    CZF: []
                                });
                                return;
                            }
                        }
                        //格式化数据
                        let formattedData = {};
                        /**
                         * 格式化指定字段数据为指定表头，并转化为数组
                         * @param field
                         * @return {Array}
                         */
                        let format = function(field){
                            let TypeTranslation = {
                                department: '养老机构',
                                home: '居家照护',
                                evaluate: '评估'
                            };
                            let formattedRowData = {};
                            for(let i in data){
                                let row = data[i];
                                let type = row.type;
                                if(! (type in formattedRowData)){
                                    formattedRowData[type] = {}
                                }
                                formattedRowData[type][MONTH_FIELD[row.month - 1]] = row[field];
                            }
                            //行汇总
                            for(let type in formattedRowData){
                                let row = formattedRowData[type];
                                let sum = 0;
                                for(let month in row){
                                    sum += row[month];
                                }
                                row.total = sum;
                            }
                            //转数组
                            let list = [];
                            for(let type in formattedRowData){
                                formattedRowData[type].type = TypeTranslation[type] || type;
                                list.push(formattedRowData[type]);
                            }
                            return list;

                        };

                        formattedData['TOTFY'] = format('TOTFY');
                        formattedData['TCZF'] = format('TCZF');
                        // console.log(formattedData);

                        if(setting.success){
                            setting.success(formattedData);
                        }
                    }
                    else{
                        if(setting.error){
                            setting.error(res);
                        }
                    }

                },
                error: (res) =>{
                    if(setting.error){
                        setting.error(res);
                    }
                },

                complete: ()=>{
                    layer.close(loadingLayer);
                }
            });
        };

        //初始化
        let defaultFormData = {
            year: new Date().getFullYear() - 1
        };
        form.val("filter-form", defaultFormData);

        //错误处理
        let errorHandler = function (res) {
            if(res.msg){
                layer.msg(res.msg, {icon: 2});
            }else if(res.status){
                layer.msg(res.status, {icon: 2});
            }else{
                layer.msg('发生了错误', {icon: 2});
            }
        };

        //日期(选择日期后直接更新)
        const NOW_DATE = new Date();
        const NOW = [NOW_DATE.getFullYear(), NOW_DATE.getMonth(), NOW_DATE.getDate()].join('-');
        laydate.render({
            elem: '#queryDate',
            type: 'year',
            value: defaultFormData.year,
            format: 'yyyy',
            isInitValue: true,
            min: '2018-1-1',
            max: NOW,
            theme: 'grid',
            done: function(value){
                fetch({
                    formData: {year: value},
                    success: (formattedData)=>{
                        //更新
                        Render.update({
                            selector:'dataTableExpense',
                            title: value + '-总费用',
                            data:formattedData['TOTFY']
                        });
                        Render.update({
                            selector:'dataTablePayment',
                            title: value  + '-医保支付费用',
                            data:formattedData['TCZF']
                        });
                    },
                    error: errorHandler
                })
            }
        });

        form.render();


        //初始拉取数据
        fetch({
            formData: defaultFormData,
            success: (formattedData)=>{
                //更新
                Render.init({
                    selector:'#dataTableExpense',
                    title:defaultFormData.year + '-总费用',
                    data:formattedData['TOTFY']
                });
                Render.init({
                    selector:'#dataTablePayment',
                    title:defaultFormData.year + '-医保支付费用',
                    data:formattedData['TCZF']
                });
            },
            error: errorHandler
        })

    })
});